package com.writing.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.writing.annotation.RequireAdmin;
import com.writing.common.Result;
import com.writing.entity.User;
import com.writing.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员控制器
 * 提供管理员专用功能
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {
    
    private final UserService userService;
    
    /**
     * 获取所有用户列表（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能查看用户列表")
    @GetMapping("/users")
    public Result<IPage<Map<String, Object>>> getAllUsers(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Integer status) {
        try {
            Page<User> page = new Page<>(current, size);
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            
            // 关键词搜索（用户名、邮箱）
            if (StringUtils.hasText(keyword)) {
                wrapper.and(w -> w.like(User::getUsername, keyword)
                        .or().like(User::getEmail, keyword)
                        .or().like(User::getNickname, keyword));
            }
            
            // 角色筛选
            if (StringUtils.hasText(role)) {
                wrapper.eq(User::getRole, role);
            }
            
            // 状态筛选
            if (status != null) {
                wrapper.eq(User::getStatus, status);
            }
            
            // 按创建时间倒序
            wrapper.orderByDesc(User::getCreatedAt);
            
            IPage<User> userPage = userService.page(page, wrapper);
            
            // 转换数据格式
            List<Map<String, Object>> userList = userPage.getRecords().stream().map(user -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", user.getId());
                map.put("username", user.getUsername());
                map.put("email", user.getEmail());
                map.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
                map.put("role", user.getRole() != null ? user.getRole() : "USER");
                map.put("status", user.getStatus());
                map.put("createdAt", user.getCreatedAt());
                map.put("lastLoginTime", user.getLastLoginTime());
                return map;
            }).collect(Collectors.toList());
            
            // 创建返回的分页对象
            Page<Map<String, Object>> resultPage = new Page<>(current, size, userPage.getTotal());
            resultPage.setRecords(userList);
            
            return Result.success(resultPage);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.error("获取用户列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改用户角色（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能修改用户角色")
    @PutMapping("/users/{userId}/role")
    public Result<Object> updateUserRole(@PathVariable Long userId, 
                                        @RequestParam String role) {
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            if (!"ADMIN".equals(role) && !"USER".equals(role)) {
                return Result.error("无效的角色");
            }
            
            user.setRole(role);
            userService.updateById(user);
            
            Map<String, Object> data = new HashMap<>();
            data.put("userId", userId);
            data.put("role", role);
            
            return Result.success("角色更新成功", data);
        } catch (Exception e) {
            return Result.error("更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 禁用/启用用户（仅管理员）
     */
    @RequireAdmin(message = "需要管理员权限才能修改用户状态")
    @PutMapping("/users/{userId}/status")
    public Result<Object> updateUserStatus(@PathVariable Long userId, 
                                          @RequestParam Integer status) {
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            if (status != 0 && status != 1) {
                return Result.error("无效的状态");
            }
            
            user.setStatus(status);
            userService.updateById(user);
            
            Map<String, Object> data = new HashMap<>();
            data.put("userId", userId);
            data.put("status", status);
            
            return Result.success("状态更新成功", data);
        } catch (Exception e) {
            return Result.error("更新失败: " + e.getMessage());
        }
    }
}

